package crm.clientManagement.managedbean;

import commonInfrastructure.accountManagement.entity.SalesmanEntity;
import commonInfrastructure.accountManagement.session.EmployeeSessionBean;
import crm.clientManagement.entity.AddressEntity;
import crm.clientManagement.entity.CompanyEntity;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import crm.clientManagement.session.CompanySessionBean;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;

@ManagedBean(name = "createNewCompanyManagedBean")
@ViewScoped
public class CreateNewCompanyManagedBean implements Serializable {

    @EJB
    CompanySessionBean companySessionBean;
    @EJB
    EmployeeSessionBean employee;
    
    private CompanyEntity company;
    private AddressEntity address;
       
    public CreateNewCompanyManagedBean() {
        company = new CompanyEntity();
        company.setCompanyStatus("Sales Lead");
        address = new AddressEntity();
    }

    public void saveNewCompany(ActionEvent event) throws IOException {
        company.setAddress(address);
        company.setIsCustomer(false);
        
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Long loginId = (Long) request.getSession().getAttribute("userId");
        SalesmanEntity user = employee.getSalesmanById(loginId);
        company.setSalesman(user);
        
        companySessionBean.saveNewCompany(company);
        
        FacesContext.getCurrentInstance().getExternalContext().getFlash().put("newCompany", company);
        FacesContext.getCurrentInstance().getExternalContext().redirect("createNewResult.xhtml");
    }

    public CompanyEntity getCompany() {
        return company;
    }

    public void setCompany(CompanyEntity company) {
        this.company = company;
    }

    /**
     * @return the address
     */
    public AddressEntity getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(AddressEntity address) {
        this.address = address;
    }

}
